package cn.fz.demo06.tools;

import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

// https://juejin.cn/post/7485669029207441423
@Slf4j
@Component
public class TestTools {
    @Value("${app.amap-key}")
    private String amapKey;
    @Tool("获取用户所在的班级")
    public String getUserClass(@P("用户姓名") String userName){
        System.out.println("用户姓名是："+userName);
        log.info("用户姓名是：{}",userName);
        return "3班";
    }

    @Tool("获取今天的天气")
    public String getWeather(@P("地址") String address){
        System.out.println("当前地址是："+address);
        log.info("当前地址是：{}",address);
        String adCode = getAdCodeByCityName(address);
        if (Objects.equals(adCode,null)){
            // throw new RuntimeException("无法获取城市编码");
            log.info("无法获取城市编码");
            return address+"-天气晴朗！";
        }
        // return "天气晴朗！";
        return getCityWeather(address);
    }

    public String getCityWeather(String city){
        String adCode = getAdCodeByCityName(city);
        if (Objects.equals(adCode,null)){
            throw new RuntimeException("无法获取城市编码");
        }
        String urlTemplate = "https://restapi.amap.com/v3/weather/weatherInfo?key=%s&city=%s";
        String requestUrl = String.format(urlTemplate,amapKey,adCode);
        String result = "天气还行";
        try {
            // 1. 创建URL对象
            URL url = new URL(requestUrl);
            // 2. 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3. 设置请求方法
            connection.setRequestMethod("GET");
            // 4. 设置连接超时（毫秒）
            connection.setConnectTimeout(5000);
            // 5. 获取响应代码
            int responseCode = connection.getResponseCode();
            // 6. 检查响应状态
            if (responseCode == HttpURLConnection.HTTP_OK){
                // 7. 读取响应内容
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = reader.readLine())!=null){
                    response.append(inputLine);
                }
                reader.close();
                // 8. 打印结果
                System.out.println("响应内容：");
                System.out.println(response);
                result = response.toString();
            }else{
                System.out.println("请求失败，响应代码：" + responseCode);
            }
            // 9. 断开连接
            connection.disconnect();
            return result;
        }catch (Exception e){
            log.error("获取城市编码和天气失败:{}",e.getMessage());
            return "天气还行吧！";
        }
    }

    private String getAdCodeByCityName(String cityName){
        Map<String,String> cityMap = new HashMap<>();
        cityMap.put("北京市","110000");
        cityMap.put("天津市","120000");
        cityMap.put("广州市","440100");
        cityMap.put("深圳市","440300");
        cityMap.put("福州市","350100");
        cityMap.put("厦门市","350200");
        cityMap.put("莆田市","350300");
        cityMap.put("三明市","350400");
        cityMap.put("泉州市","350500");
        cityMap.put("漳州市","350600");
        cityMap.put("南平市","350700");
        cityMap.put("龙岩市","350800");
        cityMap.put("宁德市","350900");
        return cityMap.getOrDefault(cityName, null);
    }
}
